package com.hzjy.api.service.impl;

import cn.tign.hz.helper.*;
import com.alibaba.fastjson.JSONObject;
import com.aspose.words.FontSettings;
import com.hzjy.api.beans.*;
import com.hzjy.api.mapper.*;
import com.hzjy.api.vo.BqUser;
import com.hzjy.common.config.RuoYiConfig;
import com.hzjy.common.core.domain.AjaxResult;
import com.hzjy.common.core.domain.entity.SysDictData;
import com.hzjy.common.enums.DelistingStatusEnum;
import com.hzjy.common.enums.TradingStatusEnum;
import com.hzjy.common.utils.*;
import com.hzjy.common.utils.bean.BeanUtils;
import com.hzjy.common.utils.file.FileUploadUtils;
import com.hzjy.framework.config.ServerConfig;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.util.*;

/**
 * 查询项目信息
 */
@Service
public class ApiProductServiceImpl {
    private static final Logger log = LoggerFactory.getLogger(ApiProductServiceImpl.class);
    @Autowired
    private ApiProductMapper apiProductMapper;
    @Autowired
    private ApiProjectMapper apiProjectMapper;
    @Autowired
    private ApiWorksMapper apiWorksMapper;
    @Autowired
    private BqUserMapper bqUserMapper;
    @Autowired
    private HzjyProjectAuthorMapper hzjyProjectAuthorMapper;
    @Autowired
    private HzjyProjectAuthorServiceImpl hzjyProjectAuthorServiceImpl;
    @Autowired
    private HzjyAgreementServiceImpl hzjyAgreementServiceImpl;
    @Autowired
    private ApiDelistServiceImpl apiDelistServiceImpl;
    @Autowired
    private HzjyDelistingSuccServiceImpl hzjyDelistingSuccServiceImpl;
    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private HzjyFileUploadRecordServiceImpl hzjyFileUploadRecordServiceImpl;
    @Autowired
    private HzjyAcceptAddressServiceImpl hzjyAcceptAddressServiceImpl;
    @Autowired
    private ApiDictServiceImpl apiDictService;
    @Autowired
    private HzjyServiceChargeServiceImpl hzjyServiceChargeService;

    /**
     * 主页获取作品集合
     *
     * @param pd
     * @return
     */
    public List<PageData> getIndexWorksList(PageData pd) {
        return apiProductMapper.getIndexWorksList(pd);
    }

    public Integer getIndexWorksNum() {
        return apiProductMapper.getIndexWorksNum();
    }

    /**
     * 主页获取项目集合
     *
     * @param pd
     * @return
     */
    public List<PageData> getIndexProjectList(PageData pd) {
        return apiProductMapper.getIndexProjectList(pd);
    }

    public Integer getIndexProjectNum() {
        return apiProductMapper.getIndexProjectNum();
    }

    /**
     * 版权交易页条件查询
     *
     * @param pd
     * @return
     */
    public Map getProjectList(PageData pd) {
        Map map = new HashMap();
        List<PageData> productList = apiProductMapper.getProductList(pd);
        Integer totalPage = apiProductMapper.getProductListNum(pd);
        map.put("productList", productList);
        map.put("totalPage", totalPage);
        map.put("currentPage", pd.get("currentPage")); //选择的页数
        return map;
    }

    /**
     * 首页搜索框
     *
     * @param pd
     * @return
     */
    public Map searchProductForIndexPage(PageData pd) {
        Map map = new HashMap();
        List<PageData> productList = apiProductMapper.getProductListBySearchInput(pd);
        Integer totalPage = apiProductMapper.getProductListNumBySearchInput(pd);
        map.put("productList", productList);
        map.put("totalPage", pd.getPageNum(totalPage, 8));
        map.put("currentPage", pd.get("currentPage")); //选择的页数
        return map;
    }

    /**
     * 获取个人详情页的挂牌各状态的数量
     */
    public Map getTradingStateNum(Long userId) {
        List<PageData> pd = apiProductMapper.getTradingStateNum(userId);
        Map map = new HashMap();
        for (PageData p : pd) {
            switch (p.get("type").toString()) {
                case "whole":  //全部挂牌
                    map.put("whole", Integer.parseInt(p.get("num").toString()));
                    break;
                case "wait": //待审核
                    map.put("wait", Integer.parseInt(p.get("num").toString()));
                    break;
                case "tradingSucc"://挂牌成功
                    map.put("tradingSucc", Integer.parseInt(p.get("num").toString()));
                    break;
                case "finalTrial"://待签订
                    map.put("finalTrial", Integer.parseInt(p.get("num").toString()));
                    break;
                case "businessSucc"://已成交
                    map.put("businessSucc", Integer.parseInt(p.get("num").toString()));
                    break;
            }
        }
        InformationDTO informationDTO = bqUserMapper.dataIntegrity(userId);
        if (informationDTO != null) {
            //实名认证
            if (informationDTO.getRealNameCertification().equals(3)) {
                informationDTO.setNameFlag(true);
            }
            //手机认证
            if (!StringUtils.isEmpty(informationDTO.getPhone())) {
                informationDTO.setPhoneFlag(true);
            }
            //邮箱认证
            if (!StringUtils.isEmpty(informationDTO.getEmail())) {
                informationDTO.setEmailFlag(true);
            }
        }
        map.put("nickName", informationDTO.getNickName());
        map.put("avatar", informationDTO.getAvatar());
        map.put("allFillInNum", informationDTO.getAllFillInNum());
        map.put("noFillInNum", informationDTO.getNoFillInNum());
        map.put("nameFlag", informationDTO.getNameFlag());
        map.put("phoneFlag", informationDTO.getPhoneFlag());
        map.put("emailFlag", informationDTO.getEmailFlag());
        map.put("realNameCertification", informationDTO.getRealNameCertification());
        return map;
    }

    /**
     * 个人详情页获取挂牌信息
     */
    public List<PageData> getMyTradingList(PageData pd) {
        List<PageData> productList = apiProductMapper.getMyTradingList(pd);
        if (!CollectionUtils.isEmpty(productList)) {
            for (PageData pageData : productList) {
                HzjyAgreement queryAgreement = new HzjyAgreement();
                queryAgreement.setProductId(pageData.get("product_id").toString());
                queryAgreement.setType(1);
                List<HzjyAgreement> hzjyAgreementList = hzjyAgreementServiceImpl.selectHzjyAgreementList(queryAgreement);
                if (!CollectionUtils.isEmpty(hzjyAgreementList)) {
                    pageData.put("contractId", hzjyAgreementList.get(0).getId());
                }
            }
        }
        return productList;
    }

    /**
     * 获取分页的总数量和页数
     *
     * @return
     */
    public PageData getMyTradingNum(PageData pd) {
        return apiProductMapper.getMyTradingNum(pd);
    }

    /**
     * 新增挂牌
     */
    @Transactional
    public void addTrading(PageData pd) {
        PageData pd2 = new PageData();
        Map map = BeanUtils.toReplaceKeyLow(pd);
        pd2.setMap(map);
        pd2.put("createTime", DateUtils.getTime());
        if (pd2.get("price") == null || Integer.parseInt(pd2.get("price").toString()) == 0) {
            pd2.put("priceType", "1");//面议
            pd2.remove("price");
        } else {
            pd2.put("price", Integer.parseInt(pd2.get("price").toString()) * 100);//单位分
            pd2.put("priceType", "0");//默认输入价格
        }
        if (Integer.parseInt(pd2.get("tradingType").toString()) == 0) {
            Object works_table = pd2.get("worksTable");
            Map workMap = (Map) works_table;
            pd2.put("productName", workMap.get("works_name"));
            apiProductMapper.insertHzjyProduct(pd2);
            pd2.put("productId", pd2.get("product_id"));
            workMap.put("productId", pd2.get("product_id"));
            workMap.put("tradingPowerAll", pd2.get("trading_power_all"));
            //著作人
            Object author = workMap.get("author");
            HzjyProjectAuthor hzjyProjectAuthor = new HzjyProjectAuthor();
            log.info("创建作品著作人信息." + JSONUtil.bean2json(hzjyProjectAuthor));
            hzjyProjectAuthor.setAuthorName(author.toString());
            hzjyProjectAuthor.setProductId(Long.valueOf(pd2.get("product_id").toString()));
            hzjyProjectAuthorServiceImpl.insertHzjyProjectAuthor(hzjyProjectAuthor);
            workMap = BeanUtils.toReplaceKeyLow(workMap);
            pd2.setMap(workMap);
            log.info("创建作品信息." + JSONUtil.map2json(workMap));
            apiWorksMapper.insertHzjyWorks(pd2);
        } else if (Integer.parseInt(pd2.get("tradingType").toString()) == 1) {
            Object project_table = pd2.get("projectTable");
            Map projectMap = (Map) project_table;
            pd2.put("productName", projectMap.get("project_name"));
            apiProductMapper.insertHzjyProduct(pd2);
            pd2.put("productId", pd2.get("product_id"));
            projectMap.put("productId", pd2.get("product_id"));
            //著作权人
            Object project_author_list = projectMap.get("project_author_list");
            List<Map> authors = (List<Map>) project_author_list;
            if (!CollectionUtils.isEmpty(authors)) {
                for (Map authorMap : authors) {
                    HzjyProjectAuthor hzjyProjectAuthor = new HzjyProjectAuthor();
                    hzjyProjectAuthor.setAuthorName(authorMap.get("author_name").toString());
                    hzjyProjectAuthor.setCertificateType(Integer.parseInt(authorMap.get("certificate_type").toString()));
                    hzjyProjectAuthor.setCertificateNumber(authorMap.get("certificate_number").toString());
                    hzjyProjectAuthor.setCountry(authorMap.get("country").toString());
                    hzjyProjectAuthor.setProvince(authorMap.get("province").toString());
                    hzjyProjectAuthor.setCity(authorMap.get("city").toString());
                    hzjyProjectAuthor.setProductId(Long.valueOf(pd2.get("product_id").toString()));
                    log.info("创建作品著作人信息." + JSONUtil.bean2json(hzjyProjectAuthor));
                    hzjyProjectAuthorServiceImpl.insertHzjyProjectAuthor(hzjyProjectAuthor);
                }
            }
            projectMap = BeanUtils.toReplaceKeyLow(projectMap);
            pd2.setMap(projectMap);
            log.info("创建项目信息." + JSONUtil.map2json(projectMap));
            apiProjectMapper.insertHzjyProject(pd2);
        }
    }

    /**
     * 修改挂牌
     */
    @Transactional
    public void editTrading(PageData pd) {
        PageData pd2 = new PageData();
        Map map = BeanUtils.toReplaceKeyLow(pd);
        pd2.setMap(map);
        if (pd2.get("price") == null || Integer.parseInt(pd2.get("price").toString()) == 0) {
            pd2.put("priceType", "1");//面议
            pd2.remove("price");
        } else {
            pd2.put("price", Integer.parseInt(pd2.get("price").toString()) * 100);//单位分
            pd2.put("priceType", "0");//默认输入价格
        }
        if (Integer.parseInt(pd2.get("tradingType").toString()) == 0) {
            Object works_table = pd2.get("worksTable");
            Map workMap = (Map) works_table;
            pd2.put("productName", workMap.get("works_name"));
            apiProductMapper.updateHzjyProduct(pd2);
            workMap.put("productId", pd2.get("productId"));
            //先删除所有著作人
            hzjyProjectAuthorServiceImpl.deleteHzjyProjectByProductId(pd2.get("productId").toString());
            //著作人
            Object author = workMap.get("author");
            HzjyProjectAuthor hzjyProjectAuthor = new HzjyProjectAuthor();
            log.info("修改作品著作人信息." + JSONUtil.bean2json(hzjyProjectAuthor));
            hzjyProjectAuthor.setAuthorName(author.toString());
            hzjyProjectAuthor.setProductId(Long.valueOf(pd2.get("productId").toString()));
            hzjyProjectAuthorServiceImpl.insertHzjyProjectAuthor(hzjyProjectAuthor);
            workMap = BeanUtils.toReplaceKeyLow(workMap);
            pd2.setMap(workMap);
            log.info("修改作品信息." + JSONUtil.map2json(workMap));
            apiWorksMapper.updateHzjyWorks(pd2);
        } else if (Integer.parseInt(pd2.get("tradingType").toString()) == 1) {
            Object project_table = pd2.get("projectTable");
            Map projectMap = (Map) project_table;
            pd2.put("productName", projectMap.get("project_name"));
            apiProductMapper.updateHzjyProduct(pd2);
            projectMap.put("productId", pd2.get("productId"));
            //先删除所有著作人
            hzjyProjectAuthorServiceImpl.deleteHzjyProjectByProductId(pd2.get("productId").toString());
            //著作权人
            Object project_author_list = projectMap.get("project_author_list");
            List<Map> authors = (List<Map>) project_author_list;
            if (!CollectionUtils.isEmpty(authors)) {
                for (Map authorMap : authors) {
                    HzjyProjectAuthor hzjyProjectAuthor = new HzjyProjectAuthor();
                    hzjyProjectAuthor.setAuthorName(authorMap.get("author_name").toString());
                    hzjyProjectAuthor.setCertificateType(Integer.parseInt(authorMap.get("certificate_type").toString()));
                    hzjyProjectAuthor.setCertificateNumber(authorMap.get("certificate_number").toString());
                    hzjyProjectAuthor.setCountry(authorMap.get("country").toString());
                    hzjyProjectAuthor.setProvince(authorMap.get("province").toString());
                    hzjyProjectAuthor.setCity(authorMap.get("city").toString());
                    hzjyProjectAuthor.setProductId(Long.valueOf(pd2.get("productId").toString()));
                    log.info("修改作品著作人信息." + JSONUtil.bean2json(hzjyProjectAuthor));
                    hzjyProjectAuthorServiceImpl.insertHzjyProjectAuthor(hzjyProjectAuthor);
                }
            }
            projectMap = BeanUtils.toReplaceKeyLow(projectMap);
            pd2.setMap(projectMap);
            log.info("修改项目信息." + JSONUtil.map2json(projectMap));
            apiProjectMapper.updateHzjyProject(pd2);
        }
    }

    /**
     * 挂牌、摘牌生成合同
     *
     * @param productId
     * @param delistId    (挂牌为空)
     * @param tradingType 1 挂牌  2摘牌
     * @param flowId      E签宝流程ID
     * @param userId      创建人
     */
    public void createTradingAgreement(Long productId, Long delistId, Integer tradingType, String flowId, String userId) {
        log.info("挂牌、摘牌生成合同信息：productId:" + productId + ",delistId:" + delistId + ",tradingType:" + tradingType);
        HzjyAgreement hzjyAgreement = new HzjyAgreement();

        //查询产品信息
        HzjyProduct hzjyProduct = apiProductMapper.selectHzjyProductById(productId);
        if (tradingType == 2) {
            hzjyAgreement.setDelistId(delistId);
            HzjyDelist hzjyDelist = apiDelistServiceImpl.selectHzjyDelistById(delistId);
            //更改摘牌状态为签约中
            if (hzjyDelist.getStatus() == 7) {
                //双方协议签约中
                hzjyDelist.setStatus(DelistingStatusEnum.SigningTwo.getCode());
                hzjyAgreement.setSaleUserId(hzjyProduct.getUserId().toString());
            } else {
                //平台协议签约中
                hzjyDelist.setStatus(DelistingStatusEnum.Signing.getCode());
                hzjyAgreement.setSaleUserId(userId);
            }
            //默认签约过期时间为1天
            hzjyDelist.setSignTimeOut(DateUtils.addDays(new Date(), 1));
            apiDelistServiceImpl.updateHzjyDelist(hzjyDelist);
        } else if (tradingType == 1) {
            hzjyAgreement.setSaleUserId(userId);
            //更改挂牌状态为签约中
            hzjyProduct.setState(TradingStatusEnum.Signing.getCode());
            //默认签约过期时间为1天
            hzjyProduct.setSignTimeOut(DateUtils.addDays(new Date(), 1));
            updateHzjyProduct(hzjyProduct);
        }
        if (hzjyProduct.getTradingType() == 0) {
            HzjyWorks queryWork = new HzjyWorks();
            queryWork.setProductId(Long.valueOf(productId));
            List<HzjyWorks> worksList = apiWorksMapper.selectHzjyWorksList(queryWork);
            if (!CollectionUtils.isEmpty(worksList)) {
                hzjyAgreement.setProductType(worksList.get(0).getWorksType());
            }
        } else if (hzjyProduct.getTradingType() == 1) {
            HzjyProject queryProject = new HzjyProject();
            queryProject.setProductId(productId.toString());
            List<HzjyProject> projectList = apiProjectMapper.selectHzjyProjectList(queryProject);
            if (!CollectionUtils.isEmpty(projectList)) {
                hzjyAgreement.setProductType(projectList.get(0).getProjectType().intValue());
                if (hzjyProduct.getTermType() == 1) {
                    hzjyAgreement.setFinishTimeDate(projectList.get(0).getPermissionType() == null ? null : projectList.get(0).getPermissionEndTime());
                }
            }
        }
        log.info("【协议签署，生成合同信息】.");
        hzjyAgreement.setDealTimeDate(new Date());
        hzjyAgreement.setProductId(productId.toString());
        hzjyAgreement.setType(tradingType);
        hzjyAgreement.setFlowId(flowId);
        hzjyAgreement.setStatus(0);
        hzjyAgreement.setUserId(userId);
        hzjyAgreementServiceImpl.insertHzjyAgreement(hzjyAgreement);
        String contractNo = hzjyAgreementServiceImpl.createContractNo(tradingType, hzjyProduct.getTradingType(),
                Integer.parseInt(DateUtils.dateTimeNow(DateUtils.YYYY)), hzjyAgreement.getId().intValue());
        hzjyAgreement.setContractNo(contractNo);
        hzjyAgreementServiceImpl.updateHzjyAgreement(hzjyAgreement);
        log.info("【合同信息生成完成】");
    }

    /**
     * 上架
     */
    public void upTrading(PageData pd) {
        apiProductMapper.upTrading(pd);
    }

    /**
     * 下架
     */
    public void lowTrading(PageData pd) {
        apiProductMapper.lowTrading(pd);
    }

    /**
     * 提交审核
     */
    public void submitApprove(PageData pd) {
        apiProductMapper.submitApprove(pd);
    }

    /**
     * 获取挂牌的产品信息
     *
     * @param productId
     * @return
     */
    public HzjyProduct getProductInfo(Long productId) {
        HzjyProduct hzjyProduct = apiProductMapper.selectHzjyProductById(productId);
        log.info("查询产品信息." + JSONUtil.bean2json(hzjyProduct));
        //处理价格 单位 分 - 元
        BigDecimal divide = new BigDecimal(hzjyProduct.getPrice().toString()).divide(new BigDecimal(100), 0, BigDecimal.ROUND_HALF_UP);
        hzjyProduct.setPrice(Integer.parseInt(divide.toString()));

        HzjyProjectAuthor hzjyProjectAuthor = new HzjyProjectAuthor();
        hzjyProjectAuthor.setProductId(productId);
        List<HzjyProjectAuthor> authorList = hzjyProjectAuthorMapper.selectHzjyProjectAuthorList(hzjyProjectAuthor);
        log.info("查询项目著作权人." + JSONUtil.list2json(authorList));
        if (hzjyProduct.getTradingType() == 1) {
            HzjyProject queryProject = new HzjyProject();
            queryProject.setProductId(productId.toString());
            List<HzjyProject> hzjyProjectList = apiProjectMapper.selectHzjyProjectList(queryProject);
            log.info("查询项目信息." + JSONUtil.list2json(hzjyProjectList));
            if (!CollectionUtils.isEmpty(hzjyProjectList)) {
                hzjyProduct.setHzjyProject(hzjyProjectList.get(0));
                hzjyProduct.setAuthorList(authorList);
                //查询作品可出售权利
                String[] salePower = hzjyProjectList.get(0).getTradingPower().split(",");
                List<String> salePowerList = Arrays.asList(salePower);
                List<String> pList = new ArrayList<String>(salePowerList);
                HzjyDelist queryDelist = new HzjyDelist();
                queryDelist.setProductId(hzjyProduct.getProductId());
                //已经摘牌申请的产品
                List<HzjyDelist> haveDelist = apiDelistServiceImpl.selectHzjyDelistList(queryDelist);

                if (hzjyProduct.getState() == TradingStatusEnum.TradingSuccess.getCode()) {
                    hzjyProduct.setSalability(hzjyProjectList.get(0).getTradingPower());
                } else if (hzjyProduct.getState() == TradingStatusEnum.PartialCompleted.getCode()) {
                    if (hzjyProduct.getTermType() == 1) {
                        //许可
                        if (hzjyProjectList.get(0).getPermissionType() == 0) {
                            //专有许可 只能摘牌一次
                            if (!CollectionUtils.isEmpty(haveDelist)) {
                                //已经有人摘牌当前许可
                                //判断当前摘牌的权利跟
                                for (HzjyDelist delist : haveDelist) {
                                    String[] delistPower = delist.getDelistPower().split(",");
                                    for (String power : delistPower) {
                                        if (salePowerList.contains(power)) {
                                            pList.remove(power);
                                        }
                                    }
                                }
                            }
                            if (CollectionUtils.isEmpty(pList)) {
                                hzjyProduct.setSalability(null);
                            } else {
                                //还有可售出权利
                                String saleP = "";
                                for (String power : pList) {
                                    saleP += power + ",";
                                }
                                saleP = saleP.substring(0, saleP.length() - 1);
                                hzjyProduct.setSalability(saleP);
                            }
                        } else if (hzjyProjectList.get(0).getPermissionType() == 1) {
                            //非专有许可
                            hzjyProduct.setSalability(hzjyProjectList.get(0).getTradingPower());
                        }
                    } else {
                        //转让 权力只能转让一次
                        if (!CollectionUtils.isEmpty(haveDelist)) {
                            //已经有人摘牌当前许可
                            //判断当前摘牌的权利跟
                            for (HzjyDelist delist : haveDelist) {
                                if (delist.getStatus() != DelistingStatusEnum.Audit.getCode() && delist.getStatus() != DelistingStatusEnum.FirstTrial.getCode()) {
                                    String[] delistPower = delist.getDelistPower().split(",");
                                    for (String power : delistPower) {
                                        if (salePowerList.contains(power)) {
                                            pList.remove(power);
                                        }
                                    }
                                }
                            }
                        }
                        if (CollectionUtils.isEmpty(pList)) {
                            hzjyProduct.setSalability(null);
                            hzjyProduct.setIsTrading(true);
                        } else {
                            //还有可售出权利
                            String saleP = "";
                            for (String power : pList) {
                                saleP += power + ",";
                            }
                            saleP = saleP.substring(0, saleP.length() - 1);
                            hzjyProduct.setSalability(saleP);
                        }
                        //转让
                        hzjyProduct.setSalability(hzjyProjectList.get(0).getTradingPower());
                    }
                }
            } else if (hzjyProduct.getState() == TradingStatusEnum.Finished.getCode()) {
                hzjyProduct.setSalability(null);
            }
        } else if (hzjyProduct.getTradingType() == 0) {
            HzjyWorks queryWorks = new HzjyWorks();
            queryWorks.setProductId(productId);
            List<HzjyWorks> hzjyWorksList = apiWorksMapper.selectHzjyWorksList(queryWorks);
            log.info("查询作品信息." + JSONUtil.list2json(hzjyWorksList));
            if (!CollectionUtils.isEmpty(hzjyWorksList)) {
                hzjyProduct.setHzjyWorks(hzjyWorksList.get(0));
                hzjyProduct.setAuthorList(authorList);
            }
        }
        log.info("当前作品的可出售权利:" + hzjyProduct.getSalability() == null ? "" : hzjyProduct.getSalability());
        return hzjyProduct;
    }

    public HzjyProduct selectProductInfo(Long productId) {
        return apiProductMapper.selectHzjyProductById(productId);
    }

    /**
     * 小程序主页作品集合
     *
     * @return
     */
    public List<PageData> wxWorksList(PageData pd) {
        List<PageData> pageData = apiProductMapper.wxWorksList(pd);
        for (PageData pageDatum : pageData) {
            if (pageDatum.get("price") != null) {
                //价格 分 - 元
                String price = pageDatum.get("price").toString();
                BigDecimal divide = new BigDecimal(price).divide(new BigDecimal(100));
                pageDatum.put("price", divide.toString());
            }
        }
        return pageData;
    }

    /**
     * 小程序主页项目集合
     *
     * @return
     */
    public List<PageData> wxProjectList(PageData pd) {

        List<PageData> pageData = apiProductMapper.wxProjectList(pd);
        for (PageData pageDatum : pageData) {
            if (pageDatum.get("price") != null) {
                //价格 分 - 元
                String price = pageDatum.get("price").toString();
                BigDecimal divide = new BigDecimal(price).divide(new BigDecimal(100));
                pageDatum.put("price", divide.toString());
            }
        }
        return pageData;
    }

    /**
     * 小程序筛选作品集合
     *
     * @param pd
     * @return
     */
    public List<PageData> wxScreeningWorksList(PageData pd) {
        List<PageData> pageData = apiProductMapper.wxScreeningWorksList(pd);
        for (PageData pageDatum : pageData) {
            if (pageDatum.get("price") != null) {
                //价格 分 - 元
                String price = pageDatum.get("price").toString();
                BigDecimal divide = new BigDecimal(price).divide(new BigDecimal(100));
                pageDatum.put("price", divide.toString());
            }
        }
        return pageData;
    }

    /**
     * 小程序筛选项目集合
     *
     * @param pd
     * @return
     */
    public List<PageData> wxScreeningProjectList(PageData pd) {
        return apiProductMapper.wxScreeningProjectList(pd);
    }

    /**
     * 新增作品
     *
     * @param hzjyWorks
     */
    public Long insertHzjyWorks(HzjyWorks hzjyWorks) {

        HzjyProduct hzjyProduct = apiProductMapper.selectHzjyProductById(hzjyWorks.getProductId());
        if (StringUtils.isNotBlank(hzjyWorks.getWorksName())) {
            hzjyProduct.setProductName(hzjyWorks.getWorksName());
        }
        apiProductMapper.updateHzjyProductByBeans(hzjyProduct);
        apiWorksMapper.insertHzjyWorksByBeans(hzjyWorks);
        return hzjyWorks.getWorksId();
    }

    /**
     * 新增项目
     *
     * @param hzjyProject
     */
    public Long addWxProject(HzjyProject hzjyProject) {

        HzjyProduct hzjyProduct = apiProductMapper.selectHzjyProductById(Long.parseLong(hzjyProject.getProductId()));
        if (StringUtils.isNotBlank(hzjyProject.getProjectName())) {
            hzjyProduct.setProductName(hzjyProject.getProjectName());
            hzjyProduct.setPermissionType(hzjyProject.getPermissionType());
            hzjyProduct.setEmpowerType((long) hzjyProject.getTradingPowerCheckAll());
            apiProductMapper.updateHzjyProductByBeans(hzjyProduct);
        }
        //著作人
        if (hzjyProject.getHzjyProjectAuthor() != null) {
            HzjyProjectAuthor hzjyProjectAuthor = hzjyProject.getHzjyProjectAuthor();
            hzjyProjectAuthor.setProductId(Long.parseLong(hzjyProject.getProductId()));
            //添加著作权人
            hzjyProjectAuthorMapper.insertHzjyProjectAuthor(hzjyProjectAuthor);
        }
        apiProjectMapper.insertHzjyProjectByBeans(hzjyProject);
        return hzjyProject.getProjectId();
    }

    /**
     * 修改产品
     *
     * @param hzjyProduct
     */
    public void updateHzjyProduct(HzjyProduct hzjyProduct) {
        apiProductMapper.updateHzjyProductByBeans(hzjyProduct);
    }

    /**
     * 修改作品
     *
     * @param hzjyWorks
     */
    public void updateWxWorks(HzjyWorks hzjyWorks) {
        HzjyProduct hzjyProduct = apiProductMapper.selectHzjyProductById(hzjyWorks.getProductId());
        hzjyProduct.setProductName(hzjyWorks.getWorksName());
        if (hzjyProduct.getState() != TradingStatusEnum.Audit.getCode()) {
            //如果是编辑时，修改状态为待审核
            hzjyProduct.setState(TradingStatusEnum.Audit.getCode());
        }
        apiProductMapper.updateHzjyProductByBeans(hzjyProduct);
        apiWorksMapper.updateHzjyWorksByBeans(hzjyWorks);
    }

    /**
     * 修改项目
     *
     * @param hzjyProject
     */
    public void updateWxProject(HzjyProject hzjyProject) {
        HzjyProduct hzjyProduct = apiProductMapper.selectHzjyProductById(Long.parseLong(hzjyProject.getProductId()));
        hzjyProduct.setProductName(hzjyProject.getProjectName());

        if (hzjyProduct.getState() != TradingStatusEnum.Audit.getCode()) {
            //如果是编辑时，修改状态为待审核
            hzjyProduct.setState(TradingStatusEnum.Audit.getCode());
        }
        //修改挂牌
        apiProductMapper.updateHzjyProductByBeans(hzjyProduct);
        //添加著作人
        HzjyProjectAuthor hzjyProjectAuthor = hzjyProject.getHzjyProjectAuthor();
        hzjyProjectAuthor.setProductId(Long.parseLong(hzjyProject.getProductId()));
        hzjyProjectAuthorServiceImpl.insertHzjyProjectAuthor(hzjyProjectAuthor);
        //添加项目
        apiProjectMapper.updateHzjyProjectByBeans(hzjyProject);
    }

    /**
     * 新增挂牌
     */
    public Long addTradingByBeans(HzjyProduct hzjyProduct) {
        hzjyProduct.setCreateTime(new Date());
        hzjyProduct.setState(2);
        hzjyProduct.setUpState(0);
        if (hzjyProduct.getPrice().equals(0)) {
            hzjyProduct.setPriceType(1);
            hzjyProduct.setPrice(null);
        } else {
            hzjyProduct.setPrice(Integer.parseInt(hzjyProduct.getPrice().toString()) * 100);
            hzjyProduct.setPriceType(0);
        }
        apiProductMapper.insertHzjyProductByBeans(hzjyProduct);
        return hzjyProduct.getProductId();

    }

    /**
     * 查询截止到当天挂牌成功的作品
     * return user_id  用户id，total 作品数量
     */
    public List<PageData> queryTradingProductByToday(Date time) {
        List<Integer> statusList = new ArrayList<>();
        PageData pd = new PageData();
        statusList.add(TradingStatusEnum.TradingSuccess.getCode());
        statusList.add(TradingStatusEnum.PartialCompleted.getCode());
        statusList.add(TradingStatusEnum.Finished.getCode());
        pd.put("time", time);
        pd.put("statusList", statusList);
        return apiProductMapper.queryHotList(pd);
    }

    /**
     * 挂牌方确认收款
     *
     * @param contractId
     * @return
     */
    @Transactional
    public AjaxResult confirmTradingPay(String contractId) {
        //查询合同信息
        HzjyAgreement hzjyAgreement = hzjyAgreementServiceImpl.selectHzjyAgreementById(Long.valueOf(contractId));
        if (hzjyAgreement == null) {
            log.error("系统异常,合同信息未获取到.");
            return AjaxResult.error(401, "合同信息未获取到");
        }
        log.info("查询摘牌申请，修改状态【挂牌方确认收款】");
        HzjyDelist hzjyDelist = apiDelistServiceImpl.selectHzjyDelistById(hzjyAgreement.getDelistId());
        if (hzjyDelist.getStatus() != DelistingStatusEnum.Delivery.getCode()) {
            log.error("确认收款失败，当前状态异常.");
            return AjaxResult.error("确认收款失败，当前状态异常");
        }
        hzjyDelist.setStatus(DelistingStatusEnum.ConfirmCollection.getCode());
        apiDelistServiceImpl.updateHzjyDelist(hzjyDelist);
        return AjaxResult.success("确认收款完成");
    }

    /**
     * 摘牌方确认收货
     *
     * @param contractId
     * @return
     */
    @Transactional
    public AjaxResult confirmDelistingPay(String contractId) {
        //查询合同信息
        HzjyAgreement hzjyAgreement = hzjyAgreementServiceImpl.selectHzjyAgreementById(Long.valueOf(contractId));
        if (hzjyAgreement == null) {
            log.error("系统异常,合同信息未获取到.");
            return AjaxResult.error(401, "合同信息未获取到");
        }
        log.info("查询摘牌申请，修改状态【挂牌方确认收款】");
        HzjyDelist hzjyDelist = apiDelistServiceImpl.selectHzjyDelistById(hzjyAgreement.getDelistId());
        if (hzjyDelist.getStatus() != DelistingStatusEnum.ConfirmCollection.getCode()) {
            log.error("确认收货失败，当前状态异常.");
            return AjaxResult.error("确认收货失败，当前状态异常");
        }
        hzjyDelist.setStatus(DelistingStatusEnum.DelistSuccess.getCode());
        apiDelistServiceImpl.updateHzjyDelist(hzjyDelist);
        log.info("【摘牌成功创建摘牌信息公告】");
        HzjyDelistingSucc hzjyDelistingSucc = new HzjyDelistingSucc();
        hzjyDelistingSucc.setDelistingId(hzjyDelist.getDelistId());
        hzjyDelistingSucc.setContractId(Long.valueOf(contractId));
        hzjyDelistingSuccServiceImpl.insertHzjyDelistingSucc(hzjyDelistingSucc);
        log.info("【摘牌成功，创建摘牌成功记录】");
        return AjaxResult.success("确认收货完成");
    }

    /**
     * 作品详情页
     *
     * @param hzjyProduct
     * @return
     */
    public HzjyProduct queryProductInfo(HzjyProduct hzjyProduct) {
        HzjyProduct newHzjyProduct = apiProductMapper.selectHzjyProductById(hzjyProduct.getProductId());
        log.info("作品详情页查询产品信息：" + JSONUtil.object2json(hzjyProduct));
        log.info("更新作品浏览次数.");
        apiProductMapper.updateSeeNum(hzjyProduct.getProductId());
        //查询是否收藏
        if (hzjyProduct.getUserId() != null) {
            HzjyCollection hzjyCollection = new HzjyCollection();
            hzjyCollection.setOwner(hzjyProduct.getUserId().toString());
            hzjyCollection.setProductId(hzjyProduct.getProductId().toString());
            Boolean flag = apiProductMapper.selectProductIsCollection(hzjyCollection);
            if (flag) {
                newHzjyProduct.setIsCollection(true);
            } else {
                newHzjyProduct.setIsCollection(false);
            }
        }
        //判断是否是当前登录用户的挂牌作品
        if (hzjyProduct.getUserId() != null) {
            if (hzjyProduct.getUserId().equals(newHzjyProduct.getUserId())) {
                newHzjyProduct.setIsTrading(true);
            } else {
                newHzjyProduct.setIsTrading(false);
            }
        }

        HzjyDelist queryDelist = new HzjyDelist();
        queryDelist.setProductId(newHzjyProduct.getProductId());
        //已经摘牌申请的产品
        List<HzjyDelist> haveDelist = apiDelistServiceImpl.selectHzjyDelistList(queryDelist);
        if (newHzjyProduct.getTradingType() == 1) {
            //项目
            HzjyProject queryProject = new HzjyProject();
            queryProject.setProductId(newHzjyProduct.getProductId().toString());
            List<HzjyProject> hzjyProjectList = apiProjectMapper.selectHzjyProjectList(queryProject);
            HzjyProject hzjyProject = hzjyProjectList.get(0);
            newHzjyProduct.setHzjyProject(hzjyProject);

            //查询作品可出售权利
            String[] salePower = hzjyProject.getTradingPower().split(",");
            List<String> salePowerList = Arrays.asList(salePower);
            List<String> pList = new ArrayList<String>(salePowerList);
            if (newHzjyProduct.getState() == TradingStatusEnum.TradingSuccess.getCode()) {
                newHzjyProduct.setSalability(hzjyProject.getTradingPower());
            } else if (newHzjyProduct.getState() == TradingStatusEnum.PartialCompleted.getCode()) {
                if (newHzjyProduct.getTermType() == 1) {
                    if (hzjyProject.getPermissionType() == 0) {
                        //专有许可 只能摘牌一次
                        if (!CollectionUtils.isEmpty(haveDelist)) {
                            //已经有人摘牌当前许可
                            //判断当前摘牌的权利跟
                            for (HzjyDelist delist : haveDelist) {
                                //判断当前登录用户是否摘牌过此挂牌
                                if (hzjyProduct.getUserId() != null){
                                    if (delist.getUserId().equals(hzjyProduct.getUserId().toString())) {
                                        if (delist.getStatus() == DelistingStatusEnum.Audit.getCode() || delist.getStatus() == DelistingStatusEnum.FirstTrial.getCode()) {
                                            //如果摘过，并且审核状态为待审核
                                            newHzjyProduct.setIsTrading(true);
                                        } else {
                                            //当摘牌已经审核通过，才移除对应的权力
                                            String[] delistPower = delist.getDelistPower().split(",");
                                            for (String power : delistPower) {
                                                if (salePowerList.contains(power)) {
                                                    pList.remove(power);
                                                }
                                            }
                                        }
                                    } else {
                                        if (delist.getStatus() != DelistingStatusEnum.Audit.getCode() && delist.getStatus() != DelistingStatusEnum.FirstTrial.getCode() && delist.getStatus() != DelistingStatusEnum.Reject.getCode()) {
                                            //当别人摘牌已经审核通过，才移除对应的权力
                                            String[] delistPower = delist.getDelistPower().split(",");
                                            for (String power : delistPower) {
                                                if (salePowerList.contains(power)) {
                                                    pList.remove(power);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        if (CollectionUtils.isEmpty(pList)) {
                            newHzjyProduct.setSalability(null);
                            newHzjyProduct.setIsTrading(true);
                        } else {
                            //还有可售出权利
                            String saleP = "";
                            for (String power : pList) {
                                saleP += power + ",";
                            }
                            saleP = saleP.substring(0, saleP.length() - 1);
                            newHzjyProduct.setSalability(saleP);
                        }
                    } else if (hzjyProject.getPermissionType() == 1) {
                        //非专有许可
                        newHzjyProduct.setSalability(hzjyProject.getTradingPower());
                    }
                } else {
                    //转让 权力只能转让一次
                    if (!CollectionUtils.isEmpty(haveDelist)) {
                        //已经有人摘牌当前许可
                        //判断当前摘牌的权利跟
                        for (HzjyDelist delist : haveDelist) {
                            if (delist.getStatus() != DelistingStatusEnum.Audit.getCode() && delist.getStatus() != DelistingStatusEnum.FirstTrial.getCode()) {
                                String[] delistPower = delist.getDelistPower().split(",");
                                for (String power : delistPower) {
                                    if (salePowerList.contains(power)) {
                                        pList.remove(power);
                                    }
                                }
                            }
                        }
                    }
                    if (CollectionUtils.isEmpty(pList)) {
                        newHzjyProduct.setSalability(null);
                        newHzjyProduct.setIsTrading(true);
                    } else {
                        //还有可售出权利
                        String saleP = "";
                        for (String power : pList) {
                            saleP += power + ",";
                        }
                        saleP = saleP.substring(0, saleP.length() - 1);
                        newHzjyProduct.setSalability(saleP);
                    }
                }
            } else if (newHzjyProduct.getState() == TradingStatusEnum.Finished.getCode()) {
                newHzjyProduct.setSalability(null);
            }

            //项目拥有权力数组
            String possessPower = hzjyProject.getPossessPower();
            if (StringUtils.isNotBlank(possessPower)) {
                String[] split = possessPower.split(",");
                hzjyProject.setPossessPowerStr(split);
            }

            //项目标的权力数组
            String salability = newHzjyProduct.getSalability();
            if (StringUtils.isNotBlank(salability)) {
                String[] split = salability.split(",");
                hzjyProject.setTradingPowerStr(split);
            }
        } else if (newHzjyProduct.getTradingType() == 0) {
            //判断当前用户是否对该作品摘过牌
            for (HzjyDelist delist : haveDelist) {
                if (hzjyProduct.getUserId() != null){
                    if (delist.getUserId().equals(hzjyProduct.getUserId().toString())) {
                        if (delist.getStatus() != DelistingStatusEnum.Reject.getCode()) {
                            //如果该用户对该作品摘过牌，并且正在审核，则状态改为true 不显示申请摘牌按钮
                            newHzjyProduct.setIsTrading(true);
                        }
                    }
                }
            }
            //作品
            HzjyWorks queryWorks = new HzjyWorks();
            queryWorks.setProductId(hzjyProduct.getProductId());
            List<HzjyWorks> hzjyWorksList = apiWorksMapper.selectHzjyWorksList(queryWorks);
            HzjyWorks hzjyWorks = hzjyWorksList.get(0);
            newHzjyProduct.setHzjyWorks(hzjyWorks);
            newHzjyProduct.setSalability(hzjyWorks.getTradingPower());
        }
        return newHzjyProduct;
    }

    /**
     * 查询所有挂牌成功切已上架的数据
     *
     * @return
     */
    public List<HzjyProduct> queryAllByTradingSuccAndUpState() {
        return apiProductMapper.selectAll();
    }

    /**
     * 挂牌生成协议
     *
     * @param productId
     */
    @Transactional
    public Integer createTradingContract(Long productId, String userId) {
        HzjyProduct hzjyProduct = selectProductInfo(productId);
        BqUser bpUser = bqUserMapper.findByUserId(hzjyProduct.getUserId().toString());
        Map<String, Object> dataMap = new HashMap<>();
        if (bpUser.getType() == 1) {
            //企业
            //乙方
            dataMap.put("userName", bpUser.getEnterpriseName());
            //法人
            dataMap.put("faRen", bpUser.getFullName());
        } else if (bpUser.getType() == 0) {
            //个人
            //乙方
            dataMap.put("userName", bpUser.getFullName());
            dataMap.put("faRen", "");
        }
        //联系电话
        dataMap.put("phone", bpUser.getPhone());
        //作品名称
        dataMap.put("productName", hzjyProduct.getProductName());
        //佣金
        dataMap.put("rate", "5");
        //开户名称
        dataMap.put("realUserName", bpUser.getFullName());
        //开户银行
        dataMap.put("bankName", bpUser.getBankName());
        //银行账号
        dataMap.put("bankNo", bpUser.getBankNum());
        //签约年
        Calendar cl = Calendar.getInstance();
        dataMap.put("dealYear", cl.get(Calendar.YEAR));
        //签约月
        dataMap.put("dealMonth", cl.get(Calendar.MONTH) + 1);
        //签约日
        dataMap.put("dealDaty", cl.get(Calendar.DAY_OF_MONTH));
        //签约日期
        dataMap.put("now", DateUtils.dateTimeNow(DateUtils.YYYYMMDD));
        String path = RuoYiConfig.getUploadPath() + "/template/";
        String templateName = "guapai_xieyi.ftl";
        String filePath2 = WordUtils.fillWord(dataMap, path, templateName);
        // 上传文件路径
        String pdfPath = RuoYiConfig.getUploadPath() + "/xieyi/test.pdf";
        //设置一个字体目录 防止Linux乱码
        FontSettings.setFontsFolder(RuoYiConfig.getUploadPath() + "/xieyi/Font/", false);
        try {
            WordUtils.word2pdf(filePath2, pdfPath);
        } catch (Exception e) {
            log.error("挂牌协议生成失败." + e.getMessage());
            return -1;
        }
        log.info("=============挂牌协议pdf生成完成=============");

        log.info("=============开始准备合同签署=============");
        try {
            log.info("---------------------获取token start------------------------------");
            //设置token缓存
            TokenHelper.getTokenData();
            String[] users = new String[2];
            log.info("---------------------创建个人账号start-------------------------------");
            //生成签名
            JSONObject personAcctJson = AccountHelper.createPersonAcct("hzjy_user" + bpUser.getUserId(),
                    bpUser.getFullName(), "CRED_PSN_CH_IDCARD", bpUser.getCardNum(), bpUser.getPhone(), bpUser.getEmail());
            String acctId = personAcctJson.getString("accountId");
            users[0] = acctId;
            log.info("---------------------acctId1-------------------------------" + acctId);
            log.info("---------------------创建个人账号end-------------------------------");
            //个人
            if (bpUser.getType() == 0) {
                log.info("---------------------创建个人印章----------------------------------");
                JSONObject orgAcctJson = SealHelper.createPersonTemplateSeal(acctId, null, "RED", 100, 100, "RECTANGLE");
                users[1] = acctId;
                log.info("-----------" + orgAcctJson.toString());
            } else if (bpUser.getType() == 1) {
                //企业
                log.info("---------------------创建机构账号start----------------------------------");
                JSONObject orgAcctJson = AccountHelper.createOrgAcct("hzjy_org" + bpUser.getUserId(),
                        acctId, bpUser.getEnterpriseName(), null, bpUser.getCreditCode());
                String orgId = orgAcctJson.getString("orgId");
                users[1] = orgId;
                log.info("---------------------创建机构印章start----------------------------------");
                JSONObject orgSealJson = SealHelper.createOrgTemplateSeal(orgId, bpUser.getEnterpriseName() + "印章", "BLUE", null, null, null, null, "TEMPLATE_ROUND", "STAR");
                String orgSealId = orgSealJson.getString("sealId");
            }
            log.info("---------------------通过上传方式创建文件start-----------------------------");
            String fileName = "华中国家版权交易中心有限公司作品挂牌协议书.pdf";
            JSONObject uploadJson = FileTemplateHelper.createFileByUpload(pdfPath, fileName, acctId);
            String uploadUrl = uploadJson.getString("uploadUrl");
            String fileId = uploadJson.getString("fileId");
            log.info("------上传文档------" + uploadJson.toString());

            log.info("---------------------文件流上传文件start---------------------------------");
            FileTemplateHelper.streamUpload(pdfPath, uploadUrl);

            log.info("---------------------一步发起签署start---------------------------------");

            JSONObject flowJson = SignHelper.oneStepFlow(acctId, fileId, fileName, users, bpUser.getType());
            String flowId = flowJson.getString("flowId");

            log.info("---------------------签署流程开启 start-----------------------------");
            SignHelper.startSignFlow(flowId);
            log.info("---------------------flowId-----------------------------" + flowId);
            createTradingAgreement(productId, null, 1, flowId, userId);
        } catch (Exception ex) {
            log.error("=============调用E签宝API异常=================" + ex.getMessage());
            ex.printStackTrace();
        }
        return 1;
    }

    /**
     * 摘牌生成协议
     *
     * @param delistId
     */
    public Integer createDelistingContract(Long delistId, String userId) {
        HzjyDelist hzjyDelist = apiDelistServiceImpl.selectHzjyDelistById(delistId);
        HzjyProduct hzjyProduct = selectProductInfo(hzjyDelist.getProductId());
        BqUser jiaUser = bqUserMapper.findByUserId(hzjyProduct.getUserId().toString());
        BqUser bpUser = bqUserMapper.findByUserId(hzjyDelist.getUserId());
        //查询收货地址
        HzjyAcceptAddress jiaAddr = new HzjyAcceptAddress();
        jiaAddr.setUserId(jiaUser.getUserId());
        jiaAddr.setState(Long.valueOf(3));
        List<HzjyAcceptAddress> jiaAddrList = hzjyAcceptAddressServiceImpl.selectHzjyAcceptAddressList(jiaAddr);
        HzjyAcceptAddress yiAddr = new HzjyAcceptAddress();
        yiAddr.setUserId(bpUser.getUserId());
        yiAddr.setState(Long.valueOf(3));
        List<HzjyAcceptAddress> yiAddrList = hzjyAcceptAddressServiceImpl.selectHzjyAcceptAddressList(jiaAddr);
        HzjyAgreement queryHzjyAgreement = new HzjyAgreement();
        queryHzjyAgreement.setDelistId(delistId);
        queryHzjyAgreement.setProductId(hzjyProduct.getProductId().toString());
        List<HzjyAgreement> list = hzjyAgreementServiceImpl.selectHzjyAgreementList(queryHzjyAgreement);
        Map<String, Object> dataMap = new HashMap<>();
        String[] jiaUserStr = new String[4];
        if (bpUser.getType() == 1) {
            //企业
            //乙方
            dataMap.put("yifang", bpUser.getEnterpriseName());

        } else if (bpUser.getType() == 0) {
            //个人
            //乙方
            dataMap.put("yifang", bpUser.getFullName());
        }
        if (jiaUser.getType() == 1) {
            //企业
            //甲方
            dataMap.put("jiafang", jiaUser.getEnterpriseName());

        } else if (jiaUser.getType() == 0) {
            //个人
            //甲方
            dataMap.put("jiafang", jiaUser.getFullName());
        }
        //乙方联系电话
        dataMap.put("yifangphone", bpUser.getPhone());
        if (!CollectionUtils.isEmpty(jiaAddrList)) {
            dataMap.put("jiafangaddr", jiaAddrList.get(0).getProvince() + jiaAddrList.get(0).getCity() + jiaAddrList.get(0).getArea());
        } else {
            dataMap.put("jiafangaddr", "");
        }
        //甲方联系电话
        dataMap.put("jiafangphone", jiaUser.getPhone());
        if (!CollectionUtils.isEmpty(yiAddrList)) {
            dataMap.put("yifangaddr", yiAddrList.get(0).getProvince() + yiAddrList.get(0).getCity() + yiAddrList.get(0).getArea());
        } else {
            dataMap.put("yifangaddr", "");
        }
        if (!CollectionUtils.isEmpty(list)) {
            //合同编号
            dataMap.put("contractNo", list.get(0).getContractNo());
        } else {
            //合同编号
            dataMap.put("contractNo", "");
        }
        //签约日期
        dataMap.put("now", DateUtils.dateTimeNow(DateUtils.YYYYMMDD));
        String path = RuoYiConfig.getUploadPath() + "/template/";
        String templateName = "zaipaixieyi.ftl";
        String filePath2 = WordUtils.fillWord(dataMap, path, templateName);
        String pdfPath = RuoYiConfig.getUploadPath() + "/xieyi/test.pdf";
        //设置一个字体目录 防止Linux乱码
        FontSettings.setFontsFolder(RuoYiConfig.getUploadPath() + "/xieyi/Font/", false);
        try {
            WordUtils.word2pdf(filePath2, pdfPath);
        } catch (Exception e) {
            log.error("摘牌协议生成失败." + e.getMessage());
            return -1;
        }
        log.info("=============摘牌协议pdf生成完成=============");

        log.info("=============开始准备摘牌合同签署=============");
        try {
            log.info("---------------------获取token start------------------------------");
            //设置token缓存
            TokenHelper.getTokenData();
            log.info("---------------------创建个人账号start-------------------------------");
            //生成签名
            //甲方
            JSONObject personAcctJson = AccountHelper.createPersonAcct("hzjy_user" + jiaUser.getUserId(),
                    jiaUser.getFullName(), "CRED_PSN_CH_IDCARD", jiaUser.getCardNum(), jiaUser.getPhone(), jiaUser.getEmail());
            String acctId = personAcctJson.getString("accountId");
            jiaUserStr[0] = acctId;
            log.info("---------------------甲方-------------------------------" + acctId);
            //乙方
            JSONObject personAcctJson2 = AccountHelper.createPersonAcct("hzjy_user" + bpUser.getUserId(),
                    bpUser.getFullName(), "CRED_PSN_CH_IDCARD", bpUser.getCardNum(), bpUser.getPhone(), bpUser.getEmail());
            String acctId2 = personAcctJson2.getString("accountId");
            jiaUserStr[1] = acctId2;
            log.info("---------------------乙方-------------------------------" + acctId2);
            log.info("---------------------创建个人账号end-------------------------------");
            //甲方公章创建
            if (jiaUser.getType() == 0) {
                log.info("---------------------创建甲方个人印章----------------------------------");
                JSONObject orgAcctJson = SealHelper.createPersonTemplateSeal(acctId, null, "RED", 100, 100, "RECTANGLE");
                jiaUserStr[2] = acctId;
                log.info("-----------" + orgAcctJson.toString());
            } else if (jiaUser.getType() == 1) {
                //企业
                log.info("---------------------创建甲方机构账号start----------------------------------");
                JSONObject orgAcctJson = AccountHelper.createOrgAcct("hzjy_org" + jiaUser.getUserId(),
                        acctId, jiaUser.getEnterpriseName(), null, jiaUser.getCreditCode());
                String orgId = orgAcctJson.getString("orgId");
                jiaUserStr[2] = orgId;
                log.info("---------------------创建甲方机构印章start----------------------------------");
                JSONObject orgSealJson = SealHelper.createOrgTemplateSeal(orgId, jiaUser.getEnterpriseName() + "印章", "BLUE", null, null, null, null, "TEMPLATE_ROUND", "STAR");
                String orgSealId = orgSealJson.getString("sealId");
            }

            //乙方公章创建
            if (bpUser.getType() == 0) {
                log.info("---------------------创建乙方个人印章----------------------------------");
                JSONObject orgAcctJson = SealHelper.createPersonTemplateSeal(acctId2, null, "RED", 100, 100, "RECTANGLE");
                jiaUserStr[3] = acctId2;
                log.info("-----------" + orgAcctJson.toString());
            } else if (bpUser.getType() == 1) {
                //企业
                log.info("---------------------创建乙方机构账号start----------------------------------");
                JSONObject orgAcctJson = AccountHelper.createOrgAcct("hzjy_org" + bpUser.getUserId(),
                        acctId2, bpUser.getEnterpriseName(), null, bpUser.getCreditCode());
                String orgId = orgAcctJson.getString("orgId");
                jiaUserStr[3] = orgId;
                log.info("---------------------创建乙方机构印章start----------------------------------");
                JSONObject orgSealJson = SealHelper.createOrgTemplateSeal(orgId, bpUser.getEnterpriseName() + "印章", "BLUE", null, null, null, null, "TEMPLATE_ROUND", "STAR");
                String orgSealId = orgSealJson.getString("sealId");
            }

            log.info("---------------------通过上传方式创建文件start-----------------------------");
            String fileName = "华中国家版权交易中心有限公司作品摘牌协议书.pdf";
            JSONObject uploadJson = FileTemplateHelper.createFileByUpload(pdfPath, fileName, null);
            String uploadUrl = uploadJson.getString("uploadUrl");
            String fileId = uploadJson.getString("fileId");
            log.info("------上传文档------" + uploadJson.toString());

            log.info("---------------------文件流上传文件start---------------------------------");
            FileTemplateHelper.streamUpload(pdfPath, uploadUrl);

            log.info("---------------------一步发起签署start---------------------------------");
            JSONObject flowJson = SignHelper.oneStepFlowByDeslist(acctId, fileId, fileName, jiaUserStr, jiaUser.getType(), bpUser.getType());
            String flowId = flowJson.getString("flowId");

            log.info("---------------------签署流程开启 start-----------------------------");
            SignHelper.startSignFlow(flowId);
            log.info("---------------------flowId-----------------------------" + flowId);
            createTradingAgreement(hzjyDelist.getProductId(), delistId, 2, flowId, userId);
        } catch (Exception ex) {
            log.error("=============调用E签宝API异常=================" + ex.getMessage());
            ex.printStackTrace();
            return -1;
        }
        return 1;
    }

    /**
     * 挂牌参数校验
     *
     * @param pd
     */
    /*public void parameterCalibration(PageData pd) {
        try {
            if (pd.get("tradingType") == null) {
                //挂牌类型
                throw new Exception("挂牌类型不能为空");
            }
            if (Integer.parseInt(pd.get("tradingType").toString()) == 1) {
                //项目挂牌
                if (pd.get("termType") == null) {
                    //项目类型
                    throw new Exception("项目挂牌，项目类型不能为空");
                }

                if (pd.get("permissionType") == null) {
                    //许可类型
                    throw new Exception("项目挂牌，许可类型不能为空");
                }

                if (pd.get("projectTable") == null) {
                    //项目表
                    throw new Exception("项目挂牌，项目表不能为空");
                }
                if (((Map) pd.get("projectTable")).get("project_name") == null) {
                    throw new Exception("项目挂牌，项目名称不能为空");
                }
                if (((Map) pd.get("projectTable")).get("project_author_list") == null) {
                    throw new Exception("项目挂牌，著作人不能为空");
                }

            } else if (Integer.parseInt(pd.get("tradingType").toString()) == 0) {
                //作品挂牌
            }
            if (pd.get("worksTable") == null) {
                throw new Exception("作品挂牌，作品表不能为空");
            }
            if (((Map) pd.get("worksTable")).get("works_name") == null) {
                throw new Exception("作品挂牌，作品名称不能为空");
            }
            if (((Map) pd.get("worksTable")).get("author") == null) {
                throw new Exception("作品挂牌，著作人不能为空");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/

    /**
     * 将base64编码集合转为图片，然后合成pdf，最后上传返回pdf文件地址
     *
     * @param imageList
     * @return
     * @throws Exception
     */
    private String imageToPdfUpload(List<Map> imageList) throws Exception {
        String path = RuoYiConfig.getUploadPath() + "/testImg/";
        if (!CollectionUtils.isEmpty(imageList)) {
            Map<Integer, String> map = new HashMap<Integer, String>();
            for (Map imgMap : imageList) {
                map.put(Integer.parseInt(imgMap.get("key").toString()), imgMap.get("value").toString());
            }
            List<String> list = new ArrayList<>();
            for (int i = 1; i <= map.size(); i++) {
                //查询文件上传的地址
                HzjyFileUploadRecord fileUpload = hzjyFileUploadRecordServiceImpl.selectHzjyFileUploadRecordById(Long.valueOf(map.get(i).toString()));
                list.add(i - 1, fileUpload.getFileUrl());
            }
            //将所有图片合成pdf
            String pdfPath = path + "test.pdf";
            Convert2Pdf.toPdf(list, pdfPath);
            //上次合成后的pdf
            File f = new File(pdfPath);
            // 上传并返回新文件名称
            FileInputStream inputStream = new FileInputStream(f);
            MultipartFile multipartFile = new MockMultipartFile("file", f.getName(), "text/plain", IOUtils.toByteArray(inputStream));
            return serverConfig.getUrl() + FileUploadUtils.upload(RuoYiConfig.getUploadPath(), multipartFile);
        }

        return null;
    }

    /**
     * 查询签约超时的挂牌
     *
     * @return
     */
    public List<HzjyProduct> querySignTimeOutProduct() {
        return apiProductMapper.querySignTimeOutProduct();
    }

    public List<HzjyProject> queryProjectByProductId(HzjyProject hzjyProject) {
        return apiProjectMapper.selectHzjyProjectList(hzjyProject);
    }

    /**
     * 查询对应挂牌作品权力数据
     *
     * @param hzjyProduct
     * @return
     */
    public HzjyProduct findTradingPower(HzjyProduct hzjyProduct) {
        HzjyProduct newHzjyProduct = apiProductMapper.selectHzjyProductById(hzjyProduct.getProductId());

        if (newHzjyProduct.getTradingType() == 1) {
            //项目
            HzjyProject queryProject = new HzjyProject();
            queryProject.setProductId(newHzjyProduct.getProductId().toString());
            List<HzjyProject> hzjyProjectList = apiProjectMapper.selectHzjyProjectList(queryProject);
            HzjyProject hzjyProject = hzjyProjectList.get(0);
            newHzjyProduct.setHzjyProject(hzjyProject);

            //查询作品可出售权利
            String[] salePower = hzjyProject.getTradingPower().split(",");
            List<String> salePowerList = Arrays.asList(salePower);
            List<String> pList = new ArrayList<String>(salePowerList);
            HzjyDelist queryDelist = new HzjyDelist();
            queryDelist.setProductId(newHzjyProduct.getProductId());
            //已经摘牌申请的产品
            List<HzjyDelist> haveDelist = apiDelistServiceImpl.selectHzjyDelistList(queryDelist);
            if (newHzjyProduct.getState() == TradingStatusEnum.TradingSuccess.getCode()) {
                newHzjyProduct.setSalability(hzjyProject.getTradingPower());
            } else if (newHzjyProduct.getState() == TradingStatusEnum.PartialCompleted.getCode()) {
                if (newHzjyProduct.getTermType() == 1) {
                    if (hzjyProject.getPermissionType() == 0) {
                        //专有许可 只能摘牌一次
                        if (!CollectionUtils.isEmpty(haveDelist)) {
                            //已经有人摘牌当前许可
                            //判断当前摘牌的权利跟
                            for (HzjyDelist delist : haveDelist) {
                                if (delist.getStatus() != DelistingStatusEnum.Audit.getCode() && delist.getStatus() != DelistingStatusEnum.FirstTrial.getCode()) {
                                    String[] delistPower = delist.getDelistPower().split(",");
                                    for (String power : delistPower) {
                                        if (salePowerList.contains(power)) {
                                            pList.remove(power);
                                        }
                                    }
                                }
                            }
                        }
                        if (CollectionUtils.isEmpty(pList)) {
                            newHzjyProduct.setSalability(null);
                        } else {
                            //还有可售出权利
                            String saleP = "";
                            for (String power : pList) {
                                saleP += power + ",";
                            }
                            saleP = saleP.substring(0, saleP.length() - 1);
                            newHzjyProduct.setSalability(saleP);
                        }
                    } else if (hzjyProject.getPermissionType() == 1) {
                        //非专有许可
                        newHzjyProduct.setSalability(hzjyProject.getTradingPower());
                    }
                } else {
                    //转让 权力只能转让一次
                    if (!CollectionUtils.isEmpty(haveDelist)) {
                        //已经有人摘牌当前许可
                        //判断当前摘牌的权利跟
                        for (HzjyDelist delist : haveDelist) {
                            if (delist.getStatus() != DelistingStatusEnum.Audit.getCode() && delist.getStatus() != DelistingStatusEnum.FirstTrial.getCode()) {
                                String[] delistPower = delist.getDelistPower().split(",");
                                for (String power : delistPower) {
                                    if (salePowerList.contains(power)) {
                                        pList.remove(power);
                                    }
                                }
                            }
                        }
                    }
                    if (CollectionUtils.isEmpty(pList)) {
                        newHzjyProduct.setSalability(null);
                    } else {
                        //还有可售出权利
                        String saleP = "";
                        for (String power : pList) {
                            saleP += power + ",";
                        }
                        saleP = saleP.substring(0, saleP.length() - 1);
                        newHzjyProduct.setSalability(saleP);
                    }
                }
            } else if (newHzjyProduct.getState() == TradingStatusEnum.PartialCompleted.getCode()) {
                newHzjyProduct.setSalability(null);
            }
        } else if (newHzjyProduct.getTradingType() == 0) {
            //作品
            HzjyWorks queryWorks = new HzjyWorks();
            queryWorks.setProductId(hzjyProduct.getProductId());
            List<HzjyWorks> hzjyWorksList = apiWorksMapper.selectHzjyWorksList(queryWorks);
            HzjyWorks hzjyWorks = hzjyWorksList.get(0);
            newHzjyProduct.setHzjyWorks(hzjyWorks);
            newHzjyProduct.setSalability(hzjyWorks.getTradingPower());
        }
        return newHzjyProduct;
    }


    /**
     * 摘牌方与平台生成协议
     *
     * @param delistId
     * @param userId
     * @return
     */
    @Transactional
    public Integer


    createDelisContract(Long delistId, String userId) {
        HzjyDelist hzjyDelist = apiDelistServiceImpl.selectHzjyDelistById(delistId);
        HzjyProduct hzjyProduct = selectProductInfo(hzjyDelist.getProductId());
        BqUser bpUser = bqUserMapper.findByUserId(hzjyDelist.getUserId().toString());
        //查询收货地址
        HzjyAcceptAddress jiaAddr = new HzjyAcceptAddress();
        jiaAddr.setUserId(bpUser.getUserId());
        jiaAddr.setState(Long.valueOf(3));
        List<HzjyAcceptAddress> jiaAddrList = hzjyAcceptAddressServiceImpl.selectHzjyAcceptAddressList(jiaAddr);
        //查询设置的手续费
        List<HzjyServiceCharge> hzjyServiceCharges = hzjyServiceChargeService.selectHzjyServiceChargeList(null);
        //查询挂牌合同编号
        HzjyAgreement productAgreement = new HzjyAgreement();
        productAgreement.setProductId(hzjyDelist.getProductId().toString());
        productAgreement.setType(1);
        List<HzjyAgreement> productAgreementList = hzjyAgreementServiceImpl.selectHzjyAgreementList(productAgreement);

        //查询摘牌合同编号
        HzjyAgreement delistAgreement = new HzjyAgreement();
        delistAgreement.setProductId(hzjyDelist.getProductId().toString());
        delistAgreement.setDelistId(delistId);
        List<HzjyAgreement> delistAgreementList = hzjyAgreementServiceImpl.selectHzjyAgreementList(delistAgreement);

        Map<String, Object> dataMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(jiaAddrList)) {
            dataMap.put("yifangaddr", jiaAddrList.get(0).getProvince() + jiaAddrList.get(0).getCity() + jiaAddrList.get(0).getArea());
        } else {
            dataMap.put("yifangaddr", "");
        }
        if (bpUser.getType() == 1) {
            //企业
            //乙方
            dataMap.put("userName", bpUser.getEnterpriseName());
            //法人
            dataMap.put("faRen", bpUser.getFullName());
            //营业执照
            dataMap.put("creditCode", bpUser.getCreditCode());
        } else if (bpUser.getType() == 0) {
            //个人
            //乙方
            dataMap.put("userName", bpUser.getFullName());
            dataMap.put("faRen", "");
            dataMap.put("creditCode", "");
        }
        //拼接字符串，摘牌权力
        String delistPower = hzjyDelist.getDelistPower();
        StringBuilder stringBuilder = new StringBuilder();
        List<SysDictData> powerTypeList = apiDictService.selectDictDataByType("power_type");
        String[] split = delistPower.split(",");
        for (String s : split) {
            for (SysDictData sysDictData : powerTypeList) {
                if (s.equals(sysDictData.getDictCode().toString())) {
                    if (stringBuilder.length() > 0) {
                        stringBuilder.append(",");
                    }
                    stringBuilder.append(sysDictData.getDictLabel());
                }
            }
        }
        //摘牌具体内容
        dataMap.put("delistPower", stringBuilder.toString());
        //挂牌方合同编号
        if (!CollectionUtils.isEmpty(productAgreementList)) {
            dataMap.put("productContractNo", productAgreementList.get(0).getContractNo());
        } else {
            dataMap.put("productContractNo", "");
        }
        //摘牌设置的手续费
        if (!CollectionUtils.isEmpty(hzjyServiceCharges)) {
            dataMap.put("delistingPrice", hzjyServiceCharges.get(0).getDelistingPrice().toString());
        } else {
            dataMap.put("delistingPrice", "");
        }

        //交割方式
        if (hzjyProduct.getTradingType() == 1) {
            if (hzjyProduct.getTermType() == 1) {
                dataMap.put("termType", "许可");
            } else {
                dataMap.put("termType", "转让");
            }
        } else {
            dataMap.put("termType", "");
        }

        //摘牌方合同编号
        if (!CollectionUtils.isEmpty(delistAgreementList)) {
            dataMap.put("contractNo", delistAgreementList.get(0).getContractNo());
        } else {
            dataMap.put("contractNo", "");
        }

        BigDecimal divide = new BigDecimal(hzjyProduct.getPrice()).divide(new BigDecimal(100));
        //挂牌作品价格
        dataMap.put("price", divide.toString());
        //将数字金额转为大写中文金额
        String bigPrice = ConvertUpMoney.toChinese(divide.toString());
        dataMap.put("bigPrice", bigPrice);
        //联系电话
        dataMap.put("phone", bpUser.getPhone());
        //作品名称
        dataMap.put("productName", hzjyProduct.getProductName());
        //签约年
        Calendar cl = Calendar.getInstance();
        dataMap.put("dealYear", cl.get(Calendar.YEAR));
        //签约月
        dataMap.put("dealMonth", cl.get(Calendar.MONTH) + 1);
        //签约日
        dataMap.put("dealDaty", cl.get(Calendar.DAY_OF_MONTH));
        //签约日期
        dataMap.put("now", DateUtils.dateTimeNow(DateUtils.YYYYMMDD));
        String path = RuoYiConfig.getUploadPath() + "/template/";
        String templateName = "zhaipai.ftl";
        String filePath2 = WordUtils.fillWord(dataMap, path, templateName);
        // 上传文件路径
        String pdfPath = RuoYiConfig.getUploadPath() + "/xieyi/test.pdf";
        //设置一个字体目录 防止Linux乱码
        FontSettings.setFontsFolder(RuoYiConfig.getUploadPath() + "/xieyi/Font/", false);
        try {
            WordUtils.word2pdf(filePath2, pdfPath);
        } catch (Exception e) {
            log.error("摘牌协议生成失败." + e.getMessage());
            return -1;
        }
        log.info("=============摘牌协议pdf生成完成=============");

        log.info("=============开始准备合同签署=============");
        try {
            log.info("---------------------获取token start------------------------------");
            //设置token缓存
            TokenHelper.getTokenData();
            String[] users = new String[2];
            log.info("---------------------创建个人账号start-------------------------------");
            //生成签名
            JSONObject personAcctJson = AccountHelper.createPersonAcct("hzjy_user" + bpUser.getUserId(),
                    bpUser.getFullName(), "CRED_PSN_CH_IDCARD", bpUser.getCardNum(), bpUser.getPhone(), bpUser.getEmail());
            String acctId = personAcctJson.getString("accountId");
            users[0] = acctId;
            log.info("---------------------acctId1-------------------------------" + acctId);
            log.info("---------------------创建个人账号end-------------------------------");
            //个人
            if (bpUser.getType() == 0) {
                log.info("---------------------创建个人印章----------------------------------");
                JSONObject orgAcctJson = SealHelper.createPersonTemplateSeal(acctId, null, "RED", 100, 100, "RECTANGLE");
                users[1] = acctId;
                log.info("-----------" + orgAcctJson.toString());
            } else if (bpUser.getType() == 1) {
                //企业
                log.info("---------------------创建机构账号start----------------------------------");
                JSONObject orgAcctJson = AccountHelper.createOrgAcct("hzjy_org" + bpUser.getUserId(),
                        acctId, bpUser.getEnterpriseName(), null, bpUser.getCreditCode());
                String orgId = orgAcctJson.getString("orgId");
                users[1] = orgId;
                log.info("---------------------创建机构印章start----------------------------------");
                JSONObject orgSealJson = SealHelper.createOrgTemplateSeal(orgId, bpUser.getEnterpriseName() + "印章", "BLUE", null, null, null, null, "TEMPLATE_ROUND", "STAR");
                String orgSealId = orgSealJson.getString("sealId");
            }
            log.info("---------------------通过上传方式创建文件start-----------------------------");
            String fileName = "华中国家版权交易中心有限公司作品摘牌协议书.pdf";
            JSONObject uploadJson = FileTemplateHelper.createFileByUpload(pdfPath, fileName, acctId);
            String uploadUrl = uploadJson.getString("uploadUrl");
            String fileId = uploadJson.getString("fileId");
            log.info("------上传文档------" + uploadJson.toString());

            log.info("---------------------文件流上传文件start---------------------------------");
            FileTemplateHelper.streamUpload(pdfPath, uploadUrl);

            log.info("---------------------一步发起签署start---------------------------------");

            JSONObject flowJson = SignHelper.oneStepFlowDeslist(acctId, fileId, fileName, users, bpUser.getType());
            String flowId = flowJson.getString("flowId");

            log.info("---------------------签署流程开启 start-----------------------------");
            SignHelper.startSignFlow(flowId);
            log.info("---------------------flowId-----------------------------" + flowId);
            createTradingAgreement(hzjyProduct.getProductId(), delistId, 2, flowId, userId);
        } catch (Exception ex) {
            log.error("=============调用E签宝API异常=================" + ex.getMessage());
            ex.printStackTrace();
        }
        return 1;
    }
}
